<template>
  <div>
    <el-form :model="currentRecord" ref="editForm" label-width="80px" :rules="formRules">
      <el-form-item label="医院名字" prop="hospitalName">
        <el-col :span="22">
          <el-input v-model="currentRecord.hospitalName" :disabled="this.mode == 'details'"
            placeholder="请输入医院名字"></el-input>
        </el-col>
      </el-form-item>

      <el-form-item label="地址" prop="address">
        <el-col :span="22">
          <el-input v-model="currentRecord.address" :disabled="this.mode == 'details'" placeholder="请输入地址"></el-input>
        </el-col>
      </el-form-item>

      <el-form-item align="center">
        <el-col :span="24">
          <el-button type="primary" :loading="editLoading" @click.native.prevent="handleSubmit">
            <i class="fa fa-save"></i> 保存
          </el-button>
        </el-col>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import HospitalsApi from '../api/hospitals'

export default {
  name: 'HospitalsEdit',
  props: {
    mode: {
      type: String
    },
    record: {
      type: Object
    }
  },
  data() {
    return {
      currentRecord: this.record,
      formRules: {
        hospitalName: [{ required: true, trigger: 'blur', message: '请输入医院名字' }],
        address: [{ required: true, trigger: 'blur', message: '请输入地址' }],
      },
      editLoading: false,

    }
  },
  watch: {
    record: function (oldValue, newValue) {
      this.currentRecord = this.record
      // this.getDetail()
    }
  },
  methods: {

    handleSubmit() {
      this.$refs['editForm'].validate(valid => {
        if (valid) {
          let newRecord = Object.assign({}, this.currentRecord)
          if (this.mode === 'add') {
            this.editLoading = true
            HospitalsApi.add(newRecord).then(rspData => {
              if (rspData.data.code === 200) {
                Message.success('新增成功')
              } else {
                Message.error(rspData.data.message)
              }
              this.editLoading = false
              this.$emit('after-edit')
            })
          } else if (this.mode === 'details') {
            this.$emit('after-edit')
          } else {
            this.editLoading = true
            HospitalsApi.update(newRecord).then(rspData => {
              if (rspData.data.code === 200) {
                Message.success('修改成功')
              } else {
                Message.error(rspData.data.message)
              }
              this.editLoading = false
              this.$emit('after-edit')
            })
          }
        } else {
          return false
        }
      })
    },
    resetFields() {
      this.$refs['editForm'].resetFields()
    }
  }
}
</script>
